package com.ssy.lingxi.member.merchant.utils;

import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.member.merchant.config.ServiceVariable;

import javax.mail.Authenticator;
import javax.mail.Message.RecipientType;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;
/**
 * 邮件工具类
 * @author 万宁
 * @version 2.0.0
 * @date 2020-09-08
 */
public class MailUtil {
    /**
     * 发送文本（HTML）邮件
     *
     * @param title   标题
     * @param content 内容
     * @param toMail  接收人
     */
    public static void sendTextMail(String title, String content, String toMail) {
        try {
            Properties props = new Properties();
            props.put("mail.smtp.host", ServiceVariable.MAIL_SMTP_HOST);
            props.put("mail.store.protocol", "smtp");
            props.put("mail.smtp.port", ServiceVariable.MAIL_SMTP_PORT);
            props.put("mail.smtp.auth", "true");

            props.put("mail.smtp.ssl.enable", true);
            props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            // socket factory来取代默认的socket factory
            // 只处理SSL的连接,对于非SSL的连接不做处理
            props.put("mail.smtp.socketFactory.fallback", "false");
            props.put("mail.smtp.socketFactory.port", ServiceVariable.MAIL_SMTP_PORT);

            Authenticator authenticator = new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(ServiceVariable.MAIL_ACCOUNT, ServiceVariable.MAIL_PASSWORD);
                }
            };

            Session session = Session.getDefaultInstance(props, authenticator);
            //这里要去掉
            //session.setDebug(true);

            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(ServiceVariable.MAIL_ACCOUNT));
            message.setSubject(title);
            message.setContent(content, "text/html; charset=utf-8");

            // 如果改成  RecipientType.BBC ， 则是单发邮件
            //          RecipientType.CC ， 则是抄送
            message.addRecipients(RecipientType.TO, toMail);

            message.setSentDate(new Date());

            Transport transport = session.getTransport("smtp");
            transport.connect(ServiceVariable.MAIL_SMTP_HOST, ServiceVariable.MAIL_USERNAME, ServiceVariable.MAIL_PASSWORD);
            transport.sendMessage(message, message.getAllRecipients());

        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ResponseCode.BUSINESS_ERROR, "邮件发送错误");
        }
    }
}
